package com.xunfeiai.core;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class XunfeiAIService {
    private static final String API_URL = "https://spark-api-open.xf-yun.com/v1/chat/completions";
    private String apiPassword;

    public XunfeiAIService(String apiPassword) {
        this.apiPassword = apiPassword;
    }

    private HttpRequest aiRequest() {
        HttpRequest request = HttpUtil.createPost(API_URL).header("Authorization", "Bearer " + apiPassword).contentType("application/json");
        return request;
    }


    public String askSpark(String q) {
        HttpRequest request = aiRequest();
        JSONObject param = new JSONObject();
        JSONArray messages = new JSONArray();
        messages.add(new JSONObject().set("role", "user").set("content", q));
        param.set("model", "lite").set("messages", messages).set("response_format", new JSONObject().set("type", "text"));
        HttpResponse response = request.body(param.toString()).execute();
        String ret = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(ret);
        String answer = jsonObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getStr("content");
        return answer;
    }
}
